package com.chaofan.messagebook.web;

import cn.hutool.crypto.digest.DigestUtil;
import com.chaofan.messagebook.bean.R;
import com.chaofan.messagebook.config.MyBatis;
import com.chaofan.messagebook.entity.Admin;
import com.chaofan.messagebook.mapper.BookMapper;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import org.apache.ibatis.session.SqlSession;

/**
 * @author 李超凡
 * @since 2022/4/3 18:44
 */
@Path("/admin")
public class AdminResource {

    @Inject
    private MyBatis myBatis;

    /**
     * 登录
     * @param account 账号
     * @param password 密码
     * @return state
     */
    @GET
    @Produces("application/json")
    @Path("/{account}/{password}")
    public String login(@PathParam("account") String account, @PathParam("password") String password) {
        try (SqlSession session = myBatis.getSession()) {
            BookMapper mapper = session.getMapper(BookMapper.class);
            Admin admin = mapper.selectByAccount(account);
            if (admin == null) {
                return R.fail("账号不存在");
            }
            if (!admin.getPassword().equals(password)) {
                return R.fail("密码错误");
            }
            return R.success("登录成功");
        }
    }

    // 管理员注册
    public String register(Admin admin) {
        try (SqlSession session = myBatis.getSession()) {
            BookMapper mapper = session.getMapper(BookMapper.class);
            Admin admin1 = mapper.selectByAccount(admin.getAccount());
            if (admin1 != null) {
                return R.fail("账号已存在");
            }
            admin.setPassword(DigestUtil.md5Hex(admin.getPassword()));
            int result = mapper.insert(admin);
            if (result == 1) return R.success("注册成功");
            return R.fail("注册失败");
        }
    }
}
